<?php

namespace app\company\controller;

use app\common\exception\BaseException;
use app\common\model\Salesman;
use app\common\model\Dealer;
use app\common\model\RegionStore;
use app\common\model\SalesmanStore;
use app\common\model\Store as StoreModel;
use app\common\controller\CompanyController;
use app\common\service\annotation\ControllerAnnotation;
use app\common\service\annotation\NodeAnnotation;
use app\company\model\DealerStore;
use app\common\model\Region1 as RegionModel;
use app\Request;
use jianyan\excel\Excel;
use PhpOffice\PhpSpreadsheet\IOFactory;
use think\App;
use think\Response;
use think\response\Json;

/**
 * @ControllerAnnotation(title="门店管理")
 */
class Store extends CompanyController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model           = new StoreModel();
        $this->joinTable       = 'region';
        $this->each            = true;
        $this->sort            = ['sort' => 'desc', 'id' => 'desc'];
        $this->fileName        = '门店导入模版';
        $this->importHeader    = [
                'id', '*门店名称', '*门店简称', '*详细地址', '*联系人', '*联系电话', '经度', '纬度','所属片区'
        ];
        $this->defaultTemplate = [
                'id', 'name', 'short_name', 'address', 'contact', 'phone', 'lon', 'lat','region_name'
        ];
        $this->noExportFields  = ['company_id', 'region_id', 'province_id', 'city_id', 'area_id', 'status', 'logo', 'sort', 'create_time', 'update_time', 'delete_time'];
    }

    public function list(): Json
    {
        list($limit, $where) = $this->buildSearchParams();
        $get     = $this->request->get();
        $storeId = [];
        foreach ($where as $k => $v) {
            if (str_contains($v[0], 'salesman_id')) {
                unset($where[$k]);
                if($storeId != []){
                    $storeId = array_intersect($storeId, SalesmanStore::where('salesman_id', $v[2])->column('store_id'));
                }else{
                    $storeId = array_merge($storeId, SalesmanStore::where('salesman_id', $v[2])->column('store_id'));
                }
            }
            if (str_contains($v[0], 'dealer_id')) {
                unset($where[$k]);
                if($storeId != []){
                    $storeId = array_intersect($storeId, DealerStore::where('dealer_id', $v[2])->column('store_id'));
                }else{
                    $storeId = array_merge($storeId, DealerStore::where('dealer_id', $v[2])->column('store_id'));
                }
            }
            if (str_contains($v[0], 'region_id')) {
                unset($where[$k]);
                if($storeId != []){
                    $storeId = array_intersect($storeId, RegionStore::where('region_id', $v[2])->column('store_id'));
                }else{
                    $storeId = array_merge($storeId, RegionStore::where('region_id', $v[2])->column('store_id'));
                }
            }
        }
        if (!empty($get['filter']) && !empty($storeId)) $where[] = ['id', 'in', $storeId];
        $list = $this->model->where($this->defaultWhere)->where($where)->order($this->sort)->paginate($limit);
        if ($this->each) $list = $this->each($list);
        return $this->success($list);
    }

    public function each($list)
    {
        return $list->each(function ($vo)
        {
            $sql           = new DealerStore();
            $bindDealerIds = $sql->where('store_id', $vo->id)->column('dealer_id');
            $vo->region    = $vo->region()->field('id,name')->find();
            $vo->dealer    = (new Dealer())->where('id', 'in', $bindDealerIds)->select();
            $vo->dealer_id = array_column($vo->dealer->toArray(), 'id');
            // 关联的业务员
            $salesmanIds     = $vo->salesman()->column('salesman_id');
            $vo->salesman    = (new Salesman())->where('id', 'in', $salesmanIds)
                                               ->select()
                                               ->each(function ($item) use ($vo)
                                               {
                                                   //                $dealerId = $item->SalesmanDealer()->value('dealer_id');
                                                   $dealerId     = $item->dealer()->value('dealer_id');
                                                   $item->dealer = (new Dealer())->where('id', $dealerId)->find();
                                                   $storeId      = $vo->id;
                                                   $salesmanId   = $item->id;
                                                   // 获取预存款金额
                                                   $item->balance = (new SalesmanStore())->where('store_id', $storeId)
                                                                                         ->where('salesman_id',
                                                                                                 $salesmanId)
                                                                                         ->value('balance');
                                               });
            $vo->salesman_id = array_column($vo->salesman->toArray(), 'id');
            return $vo;
        });
    }

    /**
     * @NodeAnnotation (title="新增")
     */
    public function add(Request $request): Json
    {
        try {
            $this->checkPost();
            $post = $request->post();
            $rule = [
                    'name|门店名称'    => 'require',
                    'address|详细地址' => 'require',
                    'contact|联系人'   => 'require',
                    'phone|联系人手机' => 'require|mobile'
            ];
            $this->validate($post, $rule);
            $post['company_id'] = $this->companyId;
            $this->model->transaction(function () use ($post)
            {
                $save = $this->model->save($post);
                // 添加业务员
                if ($save && !empty($post['salesman'])) {
                    $salesman = json_decode($post['salesman'], true);
                    $data     = array_map(function ($vo)
                    {
                        return [
                                'salesman_id'      => $vo['salesman_id'],
                                'store_id'         => $this->model->id,
                                'company_id'       => $this->companyId,
                                'settlement_type'  => !empty($vo['settlement_type']) ? $vo['settlement_type'] : 1,
                                'settlement_cycle' => !empty($vo['settlement_cycle']) ? $vo['settlement_cycle'] : 1,
                                'balance'          => !empty($vo['balance']) ? $vo['balance'] : 0,
                                'is_bill'          => !empty($vo['is_bill']) ? $vo['is_bill'] : 1
                        ];
                    }, $salesman);
                    (new DealerStore())->saveAll($data);
                }
                // 添加经销商
                if ($save && !empty($post['dealer_id'])) {
                    $dealer_id = explode(',', $post['dealer_id']);
                    $data      = array_map(function ($dealerId) use ($post)
                    {
                        return [
                                'dealer_id'  => $dealerId,
                                'store_id'   => $this->model->id,
                                'company_id' => $this->companyId
                        ];
                    }, $dealer_id);
                    (new DealerStore())->saveAll($data);
                }
                // 添加片区
                if ($save && !empty($post['region_id'])) {
                    RegionStore::create(['region_id' => $post['region_id'], 'store_id' => $this->model->id, 'company_id' => $this->companyId]);
                }
                // 添加业务员
                if ($save && !empty($post['salesman_id'])) {
                    $salesman_id = explode(',', $post['salesman_id']);
                    $data        = array_map(function ($salesmanId)
                    {
                        return [
                                'salesman_id'      => $salesmanId,
                                'store_id'         => $this->model->id,
                                'company_id'       => $this->companyId,
                                'settlement_type'  => !empty($vo['settlement_type']) ? $vo['settlement_type'] : 1,
                                'settlement_cycle' => !empty($vo['settlement_cycle']) ? $vo['settlement_cycle'] : 1,
                                'balance'          => !empty($vo['balance']) ? $vo['balance'] : 0,
                                'is_bill'          => !empty($vo['is_bill']) ? $vo['is_bill'] : 1
                        ];
                    }, $salesman_id);
                    (new SalesmanStore())->saveAll($data);
                }
            });
        } catch (\Exception $e) {
            return $this->error('新增失败:' . $e->getMessage());
        }
        return $this->success('新增成功');
    }

    /**
     * @NodeAnnotation (title="编辑")
     */
    public function edit(Request $request): Json
    {
        $this->checkPost();
        $post = $request->post();
        $rule = [
                'id' => 'require|integer'
        ];
        $this->validate($post, $rule);
        $row = $this->model->find($post['id']);
        if (!$row) return $this->error('数据不存在！');
        try {
            $this->model->transaction(function () use ($post, $row)
            {
                $row->save($post);
                // 修改业务员
                if (!empty($post['salesman'])) {
                    $salesman = json_decode($post['salesman'], true);
                    DealerStore::where('store_id', $row->id)->delete(true);
                    $data = array_map(function ($vo) use ($row)
                    {
                        return [
                                'salesman_id'      => $vo['salesman_id'],
                                'store_id'         => $row->id,
                                'company_id'       => $this->companyId,
                                'settlement_type'  => !empty($vo['settlement_type']) ? $vo['settlement_type'] : 1,
                                'settlement_cycle' => !empty($vo['settlement_cycle']) ? $vo['settlement_cycle'] : 1,
                                'balance'          => !empty($vo['balance']) ? $vo['balance'] : 0,
                                'is_bill'          => !empty($vo['is_bill']) ? $vo['is_bill'] : 1
                        ];
                    }, $salesman);
                    (new DealerStore())->saveAll($data);
                }
                // 修改绑定的经销商
                if (!empty($post['dealer_id'])) {
                    $dealer_id = explode(',', $post['dealer_id']);
                    DealerStore::where('store_id', $row->id)->delete(true);
                    $data = array_map(function ($dealerId) use ($row)
                    {
                        return [
                                'dealer_id'  => $dealerId,
                                'store_id'   => $row->id,
                                'company_id' => $this->companyId
                        ];
                    }, $dealer_id);
                    (new DealerStore())->saveAll($data);
                }
                // 修改绑定的片区
                if (!empty($post['region_id'])) {
                    RegionStore::where('store_id', $row->id)->delete(true);
                    (new RegionStore())->save([
                                                      'region_id'  => $post['region_id'],
                                                      'store_id'   => $row->id,
                                                      'company_id' => $this->companyId
                                              ]);
                }
                // 修改绑定的业务员
                if (!empty($post['salesman_id'])) {
                    $salesman_id = explode(',', $post['salesman_id']);
                    SalesmanStore::where('store_id', $row->id)->delete(true);
                    $data = array_map(function ($salesmanId) use ($row)
                    {
                        return [
                                'salesman_id' => $salesmanId,
                                'store_id'    => $row->id,
                                'company_id'  => $this->companyId
                        ];
                    }, $salesman_id);
                    (new SalesmanStore())->saveAll($data);
                }
            });
        } catch (\Exception $e) {
            return $this->error('保存失败:' . $e->getMessage());
        }
        return $this->success('保存成功');
    }


    /**
     * @NodeAnnotation(title="导入")
     */
    public function import(Request $request): Json
    {
        $this->checkPost();
        $file = $request->file('file');
        if (!$file) return $this->error('请上传文件！');
        // 保存文件到临时目录
        $savePath = $file->move('storage' . DIRECTORY_SEPARATOR . 'temp' . DIRECTORY_SEPARATOR);
        // 获取文件的完整路径
        $savePath = $savePath->getPathname();
        $data     = Excel::import($savePath, 1, false, 'Xlsx', './storage/temp/excelImg/');
        $this->model->startTrans();
        try {
            if (!$data) throw new BaseException(['message' => '文件内容为空！']);
            if (!$this->importHeader) throw new BaseException(['message'=>'请联系管理设置文件模版']);
            if (array_filter($data[0]) != $this->importHeader)  throw new BaseException(['message'=>'文件格式不正确']);
            unset($data[0]);
            $data = array_filter($data);
            $this->dealStore($data);
        } catch (\Exception $e) {
            @unlink($savePath);
            $this->model->rollback();
            return $this->error('导入失败' . $e->getMessage());
        }
        @unlink($savePath);
        $this->model->commit();
        return $this->success('导入成功！');
    }


    private function dealStore(mixed $data): void
    {
        if (empty($data)) throw new BaseException(['message' => '文件内容为空！']);

        array_walk($data, function ($vo)
        {
            $fields = $this->defaultTemplate;
            // 将$fields中的值对应到$vo上的键
            $data = array_combine($fields, $vo);
            $data['company_id'] = $this->companyId;
            $rule = [
                    'name|门店名称'       => 'require',
                    'contact|联系人'      => 'require',
            ];
            $this->validate($data, $rule);
            $data['region_id'] = (new RegionModel())->where('company_id',$this->companyId)->where(['name' => $data['region_name']])->value('id') ?? 0;
            $model = new StoreModel();
            unset($data['region_name']);
            if ($data['id']) {
                // 更新数据
                $row = $model->find($data['id']);
                if (!$row) throw new BaseException(["message" => "门店【{$data['name']}】不存在！"]);
                $row->update($data);
            } else {
                unset($data['id']);
                // 新增数据
                $storeId = $model->insertGetId($data);
                if($data['region_id']){
                    (new RegionStore())->save(['store_id' => $storeId, 'region_id' => $data['region_id'],'company_id'=>$this->companyId]);
                }
            }
        });
    }

}